<template>
  <div class="my-activities">
    <h2>我的活动</h2>
    <el-tabs v-model="activeTab">
      <el-tab-pane label="已报名" name="signed">
        <el-table :data="signedActivities" style="width: 100%">
          <el-table-column prop="title" label="活动名称"></el-table-column>
          <el-table-column prop="startTime" label="开始时间">
            <template #default="{row}">
              {{ formatDateTime(row.startTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="endTime" label="结束时间">
            <template #default="{row}">
              {{ formatDateTime(row.endTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="location" label="活动地点"></el-table-column>
          <el-table-column prop="status" label="状态">
            <template #default="{row}">
              <el-tag :type="statusTagMap[row.status]">
                {{ row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="{row}">
              <el-button
                  size="small"
                  type="success"
                  @click="checkIn(row.activityId)"
                  :disabled="row.status !== '进行中' || row.participationStatus === 1"
                  :loading="checkInLoading === row.activityId">
                {{ row.participationStatus === 1 ? '已签到' : '签到' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="已完成" name="completed">
        <el-table :data="completedActivities" style="width: 100%">
          <el-table-column prop="title" label="活动名称"></el-table-column>
          <el-table-column prop="startTime" label="开始时间">
            <template #default="{row}">
              {{ formatDateTime(row.startTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="endTime" label="结束时间">
            <template #default="{row}">
              {{ formatDateTime(row.endTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="pointsAward" label="获得积分"></el-table-column>
          <el-table-column prop="status" label="状态">
            <template #default="{row}">
              <el-tag :type="statusTagMap[row.status]">
                {{ row.status }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue'
import {ElMessage} from 'element-plus'
import axios from 'axios'
import qs from 'qs'

const activeTab = ref('signed')
const signedActivities = ref([])
const completedActivities = ref([])
// const username = localStorage.getItem('username')
const userStr = localStorage.getItem('user');
const userData = JSON.parse(userStr);
const username = userData.user.username;

const statusTagMap = {
  '待审核': 'info',
  '已发布': '',
  '进行中': 'success',
  '已结束': 'warning',
  '已取消': 'danger',
  '已完成': 'success'
}

onMounted(() => {
  getMyActivities()
})

const formatDateTime = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString()
}

const getMyActivities = async () => {
  try {
    const res = await axios.get(BASE_URL+'/api/v1/activities/myActivities', {
      params: {username},
      paramsSerializer: params => qs.stringify(params)
    })

    // 获取参与状态（假设后端返回的数据中已包含participationStatus字段）
    signedActivities.value = res.data.data
        .filter(item => item.status !== '已结束' && item.status !== '已完成')
        .map(item => ({
          ...item,
          status: getStatusText(item.status),
          participationStatus: item.participationStatus || 0 // 默认为0（未签到）
        }))

    completedActivities.value = res.data.data
        .filter(item => item.status === '已结束' || item.status === '已完成')
        .map(item => ({
          ...item,
          status: getStatusText(item.status)
        }))
  } catch (error) {
    ElMessage.error('获取活动列表失败')
  }
}

const getStatusText = (status) => {
  if (typeof status === 'number') {
    switch (status) {
      case 0:
        return '待审核'
      case 1:
        return '已发布'
      case 2:
        return '进行中'
      case 3:
        return '已结束'
      case 4:
        return '已取消'
      default:
        return '未知状态'
    }
  }
  return status
}

const checkInLoading = ref(null)

// checkIn方法
const checkIn = async (id) => {
  checkInLoading.value = id
  try {
    const data = {
      username,
      activityId: id
    }
    const response = await axios.post(BASE_URL+'/api/v1/activities/checkin', data, {
      headers: {
        'Content-Type': 'application/json'
      }
    })

    if (response.data.code === 2000) {
      ElMessage.success(response.data.message || '签到成功')
      // 立即更新本地状态
      const signedIndex = signedActivities.value.findIndex(a => a.activityId === id)
      if (signedIndex !== -1) {
        const completedActivity = {...signedActivities.value[signedIndex], participationStatus: 1}
        // 从已报名列表中移除
        signedActivities.value.splice(signedIndex, 1)
        // 添加到已完成列表
        completedActivities.value.unshift(completedActivity)
      }
    } else {
      ElMessage.warning(response.data.message || '操作未完成')
    }
  } catch (error) {
    let errorMessage = '签到失败，请稍后重试'
    if (error.response && error.response.data && error.response.data.message) {
      errorMessage = error.response.data.message
    }
    ElMessage.error(errorMessage)
  } finally {
    checkInLoading.value = null
  }
}
</script>

<style scoped>
.my-activities {
  padding: 20px;
}
</style>